
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import os
from utils.querys import *
from utils.querysqls import *


def getUser_ratings():
    user_ratings = {}
    userList = list(querysql('select * from user',[],'select'))
    historyList = list(querysql('select * from history',[],'select'))
    for user in userList:
        userId = user[0]
        userName = user[1]
        for history in historyList:
            movieId = history[1]
            try:
                existHistory = querysql('select id from history where movieId = %s and user_id = %s',[movieId,userId],'select')[0][0]
                movieIdz = queryhive('select id from catMovieData where id = %s',[movieId],'select')[0][0]
                historyCount = history[2]
                if user_ratings.get(userName,-1) == -1:
                    user_ratings[userName] = {movieIdz:historyCount}
                else:
                    user_ratings[userName][movieIdz] = historyCount

            except:
                continue

    print(user_ratings)
    return user_ratings

def user_col_filter(user_name,user_ratings,top_n=5):
    #获取目标用户的数据
    target_user_ratings = user_ratings[user_name]

    #保存相似度得分
    user_similarity_scoces = {}

    #目标用户转化为numpy
    target_user_ratings_list = np.array([
        ratings for _,ratings in target_user_ratings.items()
    ])

    #计算相似度得分
    for user,ratings in user_ratings.items():
        if user == user_name:
            continue
        #其他循环
        user_ratings_list = np.array([ratings.get(item,0) for item in target_user_ratings])
        similarity_score = cosine_similarity([user_ratings_list,target_user_ratings_list])[0][0]
        user_similarity_scoces[user] = similarity_score

    sorted_similarity_user = sorted(user_similarity_scoces.items(),key=lambda x:x[1],reverse=True)
    print(sorted_similarity_user)
    recommend_items = set()
    for similar_user,_ in sorted_similarity_user[:top_n]:
        recommend_items.update(user_ratings[similar_user].keys())


    #过滤
    recommend_items = [item for item in recommend_items if item not in target_user_ratings]
    print(recommend_items)
    return recommend_items

if __name__ == '__main__':

    user_name='userTwo'
    user_ratings = getUser_ratings()
    user_col_filter(user_name,user_ratings)


